﻿using System;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Xml;
using DNT.RavenQA.Web.Infrastructure.QueryModel;
using log4net;
using Raven.Client;

namespace DNT.RavenQA.Web.Controllers
{
    public class FeedController : ControllerBase
    {
        public FeedController(IDocumentSession session, ILog log)
            : base(session, log)
        {
        }

        public ActionResult Index()
        {
            return new RssActionResult {Feed = BuildFeed()};
        }

        private SyndicationFeed BuildFeed()
        {
            var items = new LatestQuestionsQuery().Execute(DocumentSession)
                .Take(10)
                .ToList()
                .Select(q =>
                            {
                                var item = new SyndicationItem();
                                q.Idratate(item);
                                return item;
                            });

            var feed = new SyndicationFeed("Test Feed",
                                           "This is a test feed",
                                           new Uri("http://Contoso/testfeed"),
                                           "TestFeedID",
                                           DateTime.UtcNow) {Items = items};
            return feed;
        }
    }

    public class RssActionResult : ActionResult
    {
        public SyndicationFeed Feed { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "application/rss+xml";
            var rssFormatter = new Rss20FeedFormatter(Feed);

            using (var writer = XmlWriter.Create(context.HttpContext.Response.Output))
                rssFormatter.WriteTo(writer);
        }
    }
}